package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class ApLikesBehaviorServiceImpl implements ApLikesBehaviorService {
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;

    @Override
    public ResponseResult like(LikesBehaviorDto dto) {
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        if (apBehaviorEntry == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "未获取到对应的行为实体信息");
        }
        Query query = Query.query(Criteria.where("entryId").is(apBehaviorEntry.getId()).and("articleId").is(dto.getArticleId()));
        int operation = dto.getOperation().intValue();
        if (operation == 0) {

            ApLikesBehavior likesBehavior = mongoTemplate.findOne(query, ApLikesBehavior.class);


            if (likesBehavior != null) {
                CustException.cust(AppHttpCodeEnum.DATA_EXIST, "请勿重复点赞");
            } else {
                likesBehavior = new ApLikesBehavior();
                likesBehavior.setEntryId(apBehaviorEntry.getId());
                likesBehavior.setArticleId(dto.getArticleId());
                likesBehavior.setType((short) 0);
                likesBehavior.setOperation((short) 0);
                likesBehavior.setCreatedTime(new Date());
                mongoTemplate.save(likesBehavior);

            }
        } else {
            mongoTemplate.remove(query,ApLikesBehavior.class);
        }
        return ResponseResult.okResult();
    }
}
